<template>
  <div class="pageContainer">
    <el-container class="bg-white rounded-lg">
      <el-header class="flex flex-col p-0" style="border-bottom: 1px solid #eeeeee; padding: 0;" :style="{ height: headerHeight+'px'}">
        <SearchForm @onMoreSearchChange="onMoreSearchChange" @onSearch="onSearch" @onClearSearch="onClearSearch">
          <SearchItem label="关键词">
            <el-input v-model="searchform.title" style="width: 200px;" placeholder="请输入商品名称" clearable />
          </SearchItem>
          <SearchItem label="分类">
            <el-select v-model="searchform.category_id" style="width: 200px;" placeholder="请选择分类" clearable>
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </SearchItem>
          <SearchItem label="状态">
            <el-select v-model="searchform.status" style="width: 200px;" placeholder="请选择状态" clearable>
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </SearchItem>
          <template #more>
            <SearchItem label="库存显示">
              <el-radio-group v-model="form.stock_display">
                <el-radio :value="1">显示</el-radio>
                <el-radio :value="0">隐藏</el-radio>
              </el-radio-group>
            </SearchItem>
          </template>
        </SearchForm>
        <div class="flex items-center">
          <div class="flex items-center gap-2 ml-2">
            <el-button type="primary" @click="onAdd">新增商品</el-button>
            <el-popconfirm title="确定批量删除这些商品吗？" @confirm="onMultiDelete">
              <template #reference>
                <el-button type="danger">批量删除</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm title="确定批量上架这些商品吗？" @confirm="onMultiSet({type:'上架', status:1})">
              <template #reference>
                <el-button plain type="success">上架</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm title="确定批量下架这些商品吗？" @confirm="onMultiSet({type:'下架', status:0})">
              <template #reference>
                <el-button plain type="info">下架</el-button>
              </template>
            </el-popconfirm>
          </div>
          <div class="ml-auto">
            <el-button type="primary" text @click="onSearch">
              <el-icon :size="20">
                <Refresh />
              </el-icon>
            </el-button>
          </div>
        </div>
      </el-header>
      <el-container>
        <div class="w-full">
          <el-table
            :data="tableData"
            style="width: 100%"
            @selection-change="onSelectionChange"
          >
            <el-table-column type="selection" width="40" />
            <el-table-column label="序号" width="90" align="center" fixed="left">
              <template #default="{ $index }">
                {{ (currentPage - 1) * limit + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="title" min-width="120" />
            <el-table-column label="分类" prop="category_id" min-width="60">
              <template #default="{ row }">
                {{ getCategoryName(row.category_id) }}
              </template>
            </el-table-column>
            <el-table-column label="封面" prop="cover" width="120">
              <template #default="{ row }">
                <el-popover :width="300" trigger="click" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
                  <template #reference>
                    <el-image :src="toAbsoluteUrl(row.cover)"  fit="contain" class="rounded" style="width:70px;height:50px"/>
                  </template>
                  <template #default>
                    <el-image :src="toAbsoluteUrl(row.cover)"  fit="contain" class="rounded" style="width:260px; height:240px"/>
                  </template>
                </el-popover>
                
              </template>
            </el-table-column>
            <el-table-column label="价格" min-width="120">
              <template #default="{ row }">
                <div>售价: {{ row.min_price }}</div>
                <div>原价: {{ row.min_oprice }}</div>
              </template>
            </el-table-column>
            <el-table-column label="库存" min-width="100">
              <template #default="{ row }">
                <div>库存: {{ row.stock }}</div>
                <div>预警: {{ row.min_stock }}</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status ? 'success' : 'warning'">
                  {{ row.status ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="onEdit(scope.row)">编辑</el-button>
                <el-button link type="primary" @click="onBannersEdit(scope.row)">轮播图</el-button>
                <el-popconfirm title="确定删除该商品吗？" @confirm="onDelete(scope.row)">
                  <template #reference>
                    <el-button type="primary" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <div style="height: 50px;" class="flex items-center justify-center">
            <el-pagination layout="prev, pager, next" background :current-page="currentPage" :total="totalCount" :page-size="10" @current-change="onPageChange" />
          </div>
        </div>
      </el-container>
    </el-container>

    <FormDrawer ref="drawerRef" :title="drawerTitle" @submit="onSubmit">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category_id">
          <el-select v-model="form.category_id" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品封面" prop="cover">
          <AvatarSelector v-model="form.cover" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="库存预警" prop="min_stock">
          <el-input-number v-model="form.min_stock" :min="0" />
        </el-form-item>
        <el-form-item label="销售价" prop="min_price">
          <el-input-number v-model="form.min_price" :min="0"/>
        </el-form-item>
        <el-form-item label="原价" prop="min_oprice">
          <el-input-number v-model="form.min_oprice" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">上架</el-radio>
            <el-radio :value="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="库存显示" prop="stock_display">
          <el-radio-group v-model="form.stock_display">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </FormDrawer>

    <BannersDrawer ref="bannerDrawerRef" @submit="getData()"/>
    
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import {
  getGoodsList,
  createGoods,
  updateGoods,
  deleteGoods,
  deleteeGoodsById,
  updateGoodsStatus,
  addBannersById
} from '../../api/goods'
import FormDrawer from '../../components/FormDrawer.vue'
import SearchForm from '../../components/SearchForm.vue'
import SearchItem from '../../components/SearchItem.vue'
import { useTableSearch, useForm } from '../../composables/common'
import { openFullScreenLoading, closeFullScreenLoading, toast, toAbsoluteUrl } from '../../composables/util'
import AvatarSelector from '../../components/AvatarSelector.vue'
import BannersDrawer from './BannersDrawer.vue'

// 搜索表单
const searchform = reactive({
  title: '',
  category_id: '',
  status: null
})

// 分类数据
const categories = ref([])

const statusList = [
  {
    value: 0,
    label: '下架',
  },
  {
    value: 1,
    label: '上架',
  }
]
// 查询数据成功后的回调，可以不用定义
const onGetDataSucceed = (res) => {
    if(res.data.categories) categories.value = res.data.categories
}

// 使用通用表格搜索逻辑
const {
  tableRowClassName,
  headerHeight,
  onSearch,
  getData,
  onClearSearch,
  onMoreSearchChange,
  onPageChange,
  currentPage,
  tableData,
  totalCount,
  limit
} = useTableSearch({
  searchform,
  getTableList: getGoodsList,
  onGetDataSucceed // 非必须
})

// 表单相关
const form = reactive({
  title: '',
  category_id: '',
  cover: '',
  description: '',
  unit: '',
  stock: 0,
  min_stock: 0,
  min_price: 0,
  min_oprice: 0,
  status: 1,
  stock_display: 1
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  // cover: [{ required: true, message: '请上传商品封面', trigger: 'change' }],
  unit: [{ required: true, message: '请输入商品单位', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  min_stock: [{ required: true, message: '请输入库存预警值', trigger: 'blur' }],
  min_price: [{ required: true, message: '请输入销售价', trigger: 'blur' }],
  min_oprice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
  stock_display: [{ required: true, message: '请选择库存显示状态', trigger: 'change' }]
}

// 获取分类名称
function getCategoryName(id) {
  const category = categories.value.find(item => item.id === id)
  return category ? category.name : ''
}

// 使用通用表单逻辑
const {
  formRef,
  drawerRef,
  drawerTitle,
  onAdd,
  onEdit,
  onDelete,
  onSubmit,
  onSelectionChange,
  onMultiDelete,
  onMultiSet
} = useForm({
  title: '商品',
  form,
  tableData,
  getData,
  add: createGoods,
  update: updateGoods,
  delete: deleteeGoodsById,
  updateStatus: updateGoodsStatus,
  multiDelte: deleteGoods, // 批量删除
  multiSet: (ids, params) => {
    const loading = openFullScreenLoading()
    updateGoodsStatus(ids, params.status).then(res => {
        toast("修改状态"+params.type+"成功")
       }).finally(() => {
        closeFullScreenLoading(loading)
        getData()
    })
  },
  formDataInit: (form) => {
    if(!form.id) {
        form.categories = null
    }
  }
})

const bannerDrawerRef = ref(null)
const onBannersEdit = (row) => {
  bannerDrawerRef.value.open(row.id, row.banners)
}


</script>

<style scoped>
:deep(.el-table .cell) {
    height: 50px;
    line-height: 50px;
}
</style>